#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>  // GNUstep 推荐使用 AppKit 而非 Cocoa

// 明确声明遵循 NSApplicationDelegate 协议
@interface MyAppDelegate : NSObject <NSApplicationDelegate> {
    NSWindow *window;
}
@end

@implementation MyAppDelegate

- (void)createMenu {
    NSMenu *mainMenu = [[NSMenu new] autorelease];
    NSMenuItem *appMenuItem = [[NSMenuItem new] autorelease];
    [mainMenu addItem:appMenuItem];  // 必须添加应用程序菜单条目
    
    NSMenu *appMenu = [[NSMenu new] autorelease];
    [appMenu addItemWithTitle:@"Quit"
                       action:@selector(terminate:)
                keyEquivalent:@"q"];
    [appMenuItem setSubmenu:appMenu];
    
    [NSApp setMainMenu:mainMenu];
}

- (void)createWindow {
    NSRect windowRect = NSMakeRect(100, 100, 300, 200);
    unsigned int styleMask = NSWindowStyleMaskTitled |
                            NSWindowStyleMaskMiniaturizable |
                            NSWindowStyleMaskClosable;  // 增加可关闭样式
    
    window = [[NSWindow alloc] initWithContentRect:windowRect
                                         styleMask:styleMask
                                           backing:NSBackingStoreBuffered
                                             defer:NO];
    [window setTitle:@"GNUstep Test"];
    
    // 创建按钮并设置布局
    NSButton *button = [[NSButton alloc] initWithFrame:NSMakeRect(100, 80, 100, 40)];
    [button setTitle:@"Click Me"];
    [button setBezelStyle:NSRoundRectBezelStyle];  // 设置按钮样式
    [button setTarget:self];
    [button setAction:@selector(buttonClicked:)];
    [window setContentView:button];
    [button release];  // 释放按钮
}

// 按钮点击事件（可选，用于测试交互）
- (void)buttonClicked:(id)sender {
    NSLog(@"Button clicked!");
}

// 修正代理方法（正确的生命周期回调）
- (void)applicationDidFinishLaunching:(NSNotification *)notification {
    [self createMenu];
    [self createWindow];
    [window makeKeyAndOrderFront:nil];
}

@end

int main(int argc, const char **argv) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    // GNUstep 必须先加载应用程序框架
    [NSApplication load];
    
    // 初始化应用程序并设置代理
    NSApplication *app = [NSApplication sharedApplication];
    MyAppDelegate *delegate = [[MyAppDelegate alloc] init];
    [app setDelegate:delegate];
    
    // 启动事件循环（GNUstep 推荐用这个方式）
    [app run];
    
    [delegate release];
    [pool release];
    return 0;
}
